"""
互斥锁 ：为资源引入一个状态：锁定和非锁定，这是多线程同步机制的一个最简单的方式

当某个线程要更改共享数据时，先将其“锁定”，使得其他线程不能修改，直到该线程释放资源，将资源状态变成“非锁定”，其他线程才能再次锁定该资源。互斥锁保证每次只有一个线程进行写入操作，从而保证了多线程情况下数据的正确性。
"""
from concurrent.futures import ThreadPoolExecutor
from threading import Lock


def thread_run_1(num):
    global global_num
    for i in range(num):
        lock.acquire()  # 上锁
        global_num += 1
        lock.release()  # 解锁
    print("In thread 1, the global_num is {}".format(global_num))


def thread_run_2(num):
    global global_num
    for i in range(num):
        lock.acquire()  # 上锁
        global_num += 1
        lock.release()  # 解锁
    print("In thread 2, the global_num is {}".format(global_num))


if __name__ == "__main__":
    # 定义全变共享变量
    global_num = 0
    # 创建一个互斥锁，默认是上锁状态
    lock = Lock()

    with ThreadPoolExecutor() as executor:
        for _ in range(5):
            executor.submit(thread_run_1, 100000)
            executor.submit(thread_run_2, 100000)
    print("Finally, the global_num is {}".format(global_num))

